﻿using System;
using System.IO;
using Com.PhilChuang.Utils;

namespace Com.PhilChuang.Pmvp.Model.Services.Impl
{
	public class ExceptionLogService : IExceptionLogService
	{
		private const String DAO_DIR = "logs";
		private const String DAO_FILE = "exceptions.txt";
		private static readonly String DAO_FILE_PATH = Path.Combine (DAO_DIR, DAO_FILE);

		private static readonly VersionInfo s_VersionInfo = AppServiceLocator.Instance.GetImpl<VersionInfo> ();

		private readonly IAppFile m_PhilFile = AppServiceLocator.Instance.GetImpl<IAppFile> ();

		public ExceptionLogService ()
		{
		}

		public bool HasExceptionLog
		{ get { return m_PhilFile.FileExists (DAO_FILE_PATH); } }

		public String GetExceptionLog ()
		{
			String result = null;
			m_PhilFile.FileOpenRead (
				DAO_FILE_PATH,
				s => result = StreamUtils.ToString (s, System.Text.Encoding.UTF8)
				);
			return result;
		}

		public virtual void LogException (Exception ex)
		{
			// log exception
			m_PhilFile.CreateDirectoryIfNotExists (DAO_DIR);
			//logger.Fatal (ex);
			if (ex != null)
			{
				m_PhilFile.FileAppendText (DAO_FILE_PATH,
				                           sw => {
				                           	sw.WriteLine (DateTime.UtcNow.ToString ("yyyy-MM-dd HH:mm:ss"));
											sw.WriteLine (s_VersionInfo.ToString ());
				                           	sw.WriteLine (ex.ToString ());
				                           	sw.Flush ();
				                           	sw.Close ();
				                           });
			}
		}

		public void DeleteExceptionLog ()
		{
			if (m_PhilFile.FileExists (DAO_FILE_PATH))
				m_PhilFile.FileDelete (DAO_FILE_PATH);
		}
	}
}
